<template>
  <div class="product-detail-view">
    <Header />
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-empty description="加载中..." />
    </div>
    
    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <el-empty :description="error" />
      <el-button @click="fetchProductDetail" style="margin-top: 20px;">重试</el-button>
    </div>
    
    <div class="detail-container" v-else-if="product">
      <div class="product-gallery">
        <img :src="currentImage" :alt="product.title" class="main-image" />
        <div class="thumbnail-list">
          <img 
            v-for="(img, index) in product.images" 
            :key="index" 
            :src="img" 
            :alt="'Thumbnail ' + (index + 1)"
            class="thumbnail"
            @click="currentImage = img"
          />
        </div>
      </div>
      
      <div class="product-info">
        <h1 class="product-title">{{ product.title }}</h1>
        
        <div class="price-section">
          <span class="current-price">¥{{ product.price.toLocaleString() }}</span>
          <span class="original-price" v-if="product.originalPrice">
            原价: ¥{{ product.originalPrice.toLocaleString() }}
          </span>
        </div>
        
        <div class="product-meta">
          <div class="meta-item">
            <span class="label">分类:</span>
            <span class="value">{{ product.category }}</span>
          </div>
          <div class="meta-item">
            <span class="label">成色:</span>
            <span class="value">{{ product.condition }}</span>
          </div>
          <div class="meta-item">
            <span class="label">发布时间:</span>
            <span class="value">{{ product.publishTime }}</span>
          </div>
          <div class="meta-item">
            <span class="label">所在地:</span>
            <span class="value">{{ product.location }}</span>
          </div>
        </div>
        
        <div class="description-section">
          <h3>商品描述</h3>
          <p class="product-description">{{ product.description }}</p>
        </div>
        
        <div class="action-buttons">
          <el-button type="primary" size="large" @click="handleContactSeller">
            <el-icon><ChatDotRound /></el-icon>
            联系卖家
          </el-button>
          <el-button type="success" size="large" @click="handleAddToCart">
            <el-icon><ShoppingCart /></el-icon>
            加入购物车
          </el-button>
          <el-button type="warning" size="large" @click="handleMakeOffer">
            <el-icon><PriceTag /></el-icon>
            我要砍价
          </el-button>
        </div>
        
        <div class="seller-info">
          <h3>卖家信息</h3>
          <div class="seller-details">
            <div class="seller-avatar">
              <el-avatar :size="50" :src="product.seller.avatar" />
            </div>
            <div class="seller-text">
              <p class="seller-name">{{ product.seller.username }}</p>
              <!-- <p class="seller-rating">信誉: ⭐⭐⭐⭐⭐ (4.8)</p> -->
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <Footer />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ChatDotRound, ShoppingCart, PriceTag } from '@element-plus/icons-vue'
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'
import { getProductDetail } from '@/api/product'
import { addToCart } from '@/api/cart'
import { getUserInfoById } from '@/api/auth'  // 导入新的API函数

const route = useRoute()
const productId = route.params.id
const product = ref(null)
const currentImage = ref('')
const loading = ref(false)
const error = ref('')
const sellerInfo = ref(null) // 添加卖家信息状态

// 从后端获取商品详情
const fetchProductDetail = async () => {
  loading.value = true
  error.value = ''
  try {
    const response = await getProductDetail(productId)
    
    // 处理后端返回的标准格式响应
    if (response && response.code === 200) {
      product.value = response.data
      
      // 处理图片URL
      if (product.value.images && product.value.images.length > 0) {
        // 确保图片URL是完整的并且格式正确
        product.value.images = product.value.images.map(img => {
          // 处理可能的两种情况：img是对象或者直接是URL字符串
          const imgUrl = img.image || img;
          
          // 如果是相对路径，添加基础URL
          if (imgUrl && typeof imgUrl === 'string' && !imgUrl.startsWith('http') && !imgUrl.startsWith('data:')) {
            return `http://127.0.0.1:8000${imgUrl}`;
          }
          return imgUrl;
        });
        
        // 设置第一张图片为当前显示的图片
        currentImage.value = product.value.images[0];
      }
      
      // 获取卖家实时信息
      await fetchSellerInfo(product.value.seller.id)
    } else {
      error.value = '获取商品详情失败'
    }
  } catch (err) {
    error.value = '网络错误，请稍后重试'
    console.error('Fetch product detail error:', err)
  } finally {
    loading.value = false
  }
}

// 实时获取卖家信息
const fetchSellerInfo = async (sellerId) => {
  try {
    // 使用新的API根据用户ID获取卖家信息
    const response = await getUserInfoById(sellerId)
    
    if (response && response.code === 200) {
      // 处理头像URL - 如果是相对路径，添加基础URL
      let avatarUrl = response.data.avatar || ''
      if (avatarUrl && !avatarUrl.startsWith('http') && !avatarUrl.startsWith('data:')) {
        avatarUrl = `http://127.0.0.1:8000${avatarUrl}`
      }
      
      sellerInfo.value = {
        id: response.data.id,
        username: response.data.username || '',
        avatar: avatarUrl,
        bio: response.data.bio || '',
        email: response.data.email || '',
        phone: response.data.phone || ''
      }
      
      // 如果商品详情中的卖家信息不完整，用实时获取的信息更新
      if (product.value && product.value.seller) {
        product.value.seller.username = sellerInfo.value.username
        product.value.seller.avatar = sellerInfo.value.avatar
      }
    }
  } catch (err) {
    console.error('获取卖家信息失败:', err)
    // 如果获取卖家信息失败，保持原有的商品详情信息
  }
}

onMounted(() => {
  fetchProductDetail()
})

const handleContactSeller = () => {
  ElMessage.success('已发送联系请求给卖家')
}

const handleAddToCart = async () => {
  try {
    const response = await addToCart({ product: product.value.id })
    
    if (response && response.code === 200) {
      ElMessage.success('商品已加入购物车')
    } else {
      ElMessage.error('加入购物车失败')
    }
  } catch (err) {
    console.error('加入购物车失败:', err)
    ElMessage.error('加入购物车失败，请稍后重试')
  }
}

const handleMakeOffer = () => {
  ElMessage.info('砍价功能开发中...')
}
</script>

<style scoped>
.product-detail-view {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.detail-container {
  flex: 1;
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 40px;
}

.product-gallery {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.main-image {
  width: 100%;
  height: 400px;
  object-fit: cover;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.thumbnail-list {
  display: flex;
  gap: 10px;
}

.thumbnail {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.2s;
}

.thumbnail:hover {
  transform: scale(1.1);
}

.product-info {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.product-title {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.price-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.current-price {
  font-size: 32px;
  font-weight: bold;
  color: #e74c3c;
}

.original-price {
  font-size: 16px;
  color: #999;
  text-decoration: line-through;
}

.product-meta {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.meta-item {
  display: flex;
  gap: 8px;
}

.meta-item .label {
  font-weight: 500;
  color: #666;
  min-width: 60px;
}

.meta-item .value {
  color: #333;
}

.description-section h3 {
  margin: 0 0 12px 0;
  color: #333;
}

.product-description {
  line-height: 1.6;
  color: #666;
  margin: 0;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-buttons .el-button {
  flex: 1;
}

.seller-info h3 {
  margin: 0 0 16px 0;
  color: #333;
}

.seller-details {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.seller-name {
  font-weight: 500;
  margin: 0 0 4px 0;
  color: #333;
}

.seller-rating {
  margin: 0;
  color: #666;
}
</style>